# -*- coding:utf-8 -*-

import struct,codecs,os
from win32com.client import Dispatch

xls=Dispatch('Excel.Application')
xls.Visible=0
xls.Workbooks.Add()

fp=open('LOC_0uk.tx','rb')
pointerend=struct.unpack('H',fp.read(2))[0]
tar=codecs.open('LOC_0uk.tx.txt','wb','utf16')

for i in xrange(0,pointerend,2):
        fp.seek(i)
        offset=struct.unpack('H',fp.read(2))[0]
        if offset==0xffff:
                continue
        fp.seek(offset)
        string=[]
        while True:
                newoffset=fp.tell()
                byte=fp.read(1)
                if byte=='\x00':
                        break
                elif byte=='\x0a':
                        string.append('\r\n')
                elif ord(byte)<0x80:
                        string.append(byte)
                else:
                        fp.seek(newoffset)
                        word=fp.read(2).decode('sjis')
                        string.append(word)
        print ''.join(string)
        tar.write('No.%d'%(i/2)+'\r\n'+u'－'*18+'\r\n'+''.join(string)+'\r\n'+u'－'*18+'\r\n'*2)
        xls.Cells(1,1).Value=u'日文'
        xls.Cells(1,2).Value=u'译文'
        xls.Cells(1,3).Value=u'备注'
        xls.Cells(1,1).ColumnWidth=55
        xls.Cells(1,2).ColumnWidth=55
        xls.Cells(1,3).ColumnWidth=30
        xls.Cells(i/2+2,1).Value=''.join(string)
        xls.Cells(i/2+2,2).Value=''.join(string)

book=xls.Workbooks(1)
book.SaveAs(os.getcwd()+os.sep+'LOC_0uk.tx'+'.xls')
fp.close()
tar.close()
xls.Quit()